package org.springframework.samples.petclinic.user;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@Controller
public class LoginController {

	private final UserRepository users;

	public LoginController(UserRepository users) {
		this.users = users;
	}

	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
		dataBinder.setDisallowedFields("id");
	}

	@RequestMapping(value = { "/" }, method = RequestMethod.GET)
	public String index(Model model, HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		model.addAttribute("user", user);
		return "welcome";
	}

	@GetMapping("/login")
	public String initLoginForm(Map<String, Object> model) {
		User user = new User();
		model.put("user", user);
		return "login";
	}

	@GetMapping("/users")
	public String processFindForm(@Valid User user, BindingResult result, Model model, HttpServletRequest request) {
		if (result.hasErrors()) {
			return "login";
		}

		// 在数据库中查找user
		User realindb = users.findByUsernameAndPassword(user.getUsername(), user.getPassword());

		if (realindb == null) {
			result.rejectValue("password", "notFound", "not found");
			return "login";
		}

		model.addAttribute("user", realindb);
		request.getSession().setAttribute("user", realindb);
		return "redirect:/welcome";
	}

}
